#include "ReaderPriorityLock.h"



namespace Zaf {
namespace Sync {



ReaderPriorityLock::ReaderPriorityLock() {

	m_readerCount = 0;

	m_readerCountLock = CreateSemaphore(nullptr, 1, 1, nullptr);
	m_writerLock = CreateSemaphore(nullptr, 1, 1, nullptr);
}



ReaderPriorityLock::~ReaderPriorityLock() {

	CloseHandle(m_readerCountLock);
	CloseHandle(m_writerLock);
}



void ReaderPriorityLock::ReaderEnter() {

	P(m_readerCountLock);

	if (m_readerCount == 0) {
		P(m_writerLock);
	}

	++m_readerCount;

	V(m_readerCountLock);
}



void ReaderPriorityLock::ReaderLeave() {

	P(m_readerCountLock);

	--m_readerCount;

	if (m_readerCount == 0) {
		V(m_writerLock);
	}

	V(m_readerCountLock);
}



void ReaderPriorityLock::WriterEnter() {

	P(m_writerLock);
}



void ReaderPriorityLock::WriterLeave() {

	V(m_writerLock);
}


}
}